/*
 * Android Runner is a multiplayer GPS game fully written by Xurxo Mendez Perez
 * 
 * Copyright (C) 2009 Xurxo Mendez Perez
 *   
 * This file is part of Android Runner.
 * 
 * Android Runner is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Android Runner is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Android Runner.  If not, see <http://www.gnu.org/licenses/>.
 */

package es.sonxurxo.androidrunner.model.persistence.message.accessor;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;

import es.sonxurxo.androidrunner.model.persistence.game.entity.Game;
import es.sonxurxo.androidrunner.model.persistence.message.entity.Message;
import es.sonxurxo.androidrunner.model.persistence.player.entity.Player;
import es.sonxurxo.androidrunner.model.persistence.util.accessor.GenericAccessorHibernate;

/**
 * 
 * @author "Xurxo Mendez Perez"
 *
 */
public class MessageAccessorHibernate 
	extends GenericAccessorHibernate<Message, Long> 
	implements MessageAccessor {

	@SuppressWarnings("unchecked")
	public List<Message> findByReceiverAndGame(Player receiver, Game game) {
		
		return getSession().createQuery(
				"SELECT m FROM Message m "
				+ "WHERE m.receiver = :receiver " +
						"AND m.game = :game ORDER BY m.date").setParameter(
						"receiver", receiver).setParameter(
								"game", game).list();
	}
	
	@SuppressWarnings("unchecked")
	public List<Message> findByGame(Game game) {
		
		return getSession().createQuery(
				"SELECT m FROM Message m "
				+ "WHERE m.game = :game ORDER BY m.date").setParameter(
								"game", game).list();
	}

	@SuppressWarnings("unchecked")
	public List<Message> findByGameAndNotInList(Game game,
			List<Long> excludedIds) {
		Criteria criteria = getSession().createCriteria(Message.class);
		criteria.add(Restrictions.eq("game", game));
		if (excludedIds != null && excludedIds.size() != 0) {
			criteria.add(Restrictions.not(Restrictions.in("messageId", excludedIds)));
		}
		return criteria.list();
//		return getSession().createQuery(
//				"SELECT m FROM Message m "
//				+ "WHERE m.game = :game and m.messageId not in (:excludedIds) ORDER BY m.date").setParameter(
//								"game", game).setParameterList(
//										"excludedIds", excludedIds).list();
	}
}
